package tacos.web.api;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.rest.webmvc.RepositoryRestController;
import org.springframework.hateoas.CollectionModel;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import tacos.Taco;
import tacos.data.TacoRepository;

import java.util.List;

import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;
import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn;

@RepositoryRestController
public class RecentTacosController {
  private TacoRepository tacoRepo;

  public RecentTacosController(TacoRepository tacoRepo) {
    this.tacoRepo = tacoRepo;
  }

  /**
   * 虽然@GetMapping映射到了“/tacos/recent”路径，但是类级别的@Repository RestController注解会确保这个路径添加
   * Spring Data REST的基础路径作为前缀。按照我们的配置，recentTacos()方法将会处理针对“/api/tacos/recent”的GET请求。
   * */
  @GetMapping(path="/tacos/recent", produces="application/hal+json")
  public ResponseEntity<CollectionModel<TacoResource>> recentTacos() {
    PageRequest page = PageRequest.of(
            0, 12, Sort.by("createdAt").descending());
    List<Taco> tacos = tacoRepo.findAll(page).getContent();

    CollectionModel<TacoResource> tacoResources =
            new TacoResourceAssembler(RecentTacosController.class, TacoResource.class).toCollectionModel(tacos);

    tacoResources.add(
            linkTo(methodOn(RecentTacosController.class).recentTacos())
                    .withRel("recents"));
    return new ResponseEntity<>(tacoResources, HttpStatus.OK);
  }

}